<template>
  <CompOperate
    :field="field"
    :designer="designer"
    :design-state="designState"
    :parent-list="parentList"
    :parent-widget="parentWidget"
    :sub-form-row-id="subFormRowId"
    :sub-form-row-index="subFormRowIndex"
    :sub-form-col-index="subFormColIndex"
    :index-of-parent-list="indexOfParentList"
    :display-style="field.options.displayStyle"
  >
    <div
      class="scene-window-widget"
      :style="getStyle('area')"
      :data-number="step"
    >
      <div class="window-area">
        <div class="replenish" v-if="optionsInfo['replenishShown']">
          <ScrollX>{{ optionsInfo.replenishContent }}</ScrollX>
        </div>
        <div class="window-info flex-box">
          <div
            class="flex-box-left-1 flex-item"
            v-if="optionsInfo['roomNumberShown']"
            :style="getStyle('room')"
          >
            <div
              class="flex-title"
              v-if="optionsInfo['winNumberShow']"
              :style="getStyle('windowTit')"
            >
              <ScrollX>{{ optionsInfo["winNumberTit"] || "窗口号" }}</ScrollX>
            </div>
            <div
              class="flex-number"
              :class="{ 'flex-number-style': optionsInfo['winNumberShow'] }"
              :style="getStyle('number')"
            >
              {{
                optionsInfo["roomNumberAuto"]
                  ? getWindowDeptInfo[optionsInfo["roomNoKey"]] ||
                    getWindowDeptInfo["roomNo"]
                  : optionsInfo["roomNumber"]
              }}
            </div>
          </div>
          <div
            class="flex-box-right-1"
            :class="optionsInfo.shadowShown ? optionsInfo['shadowClass'] : ''"
          >
            <div
              class="title"
              :class="
                optionsInfo['borderShown'] ? optionsInfo['borderClass'] : ''
              "
              :style="getStyle('title')"
            >
              {{ optionsInfo["patientListTitle"] || "当前待取药的患者" }}
            </div>
            <div
              class="content-area"
              :key="`patient_${widgetKey}`"
              :data-key="`patient_${widgetKey}`"
              :style="getStyle('patientListBackground')"
            >
              <vue-seamless-scroll
                class="scroll"
                :hoverStop="false"
                :data="getRoomDoctorInfo"
                @ScrollEnd="handleScrollEnd"
                :ref="`scroll-${widgetKey}`"
                :class-option="classOptionPatient(originalInfo || [])"
              >
                <div class="inside-content">
                  <template v-if="!!getRoomDoctorInfo?.length">
                    <template
                      v-for="(patientItem, patientKey) in getRoomDoctorInfo"
                    >
                      <div
                        class="wait-patient-inside"
                        :style="getStyle('waitPatient')"
                      >
                        <template
                          v-for="(childItem, childKey) in getPatientChildList(
                            patientItem
                          )"
                        >
                          <div
                            class="child-item"
                            v-html="getPatientContent(childItem)"
                          />
                        </template>
                      </div>
                    </template>
                  </template>
                  <template v-else>
                    <div class="wait-patient-inside-empty" />
                  </template>
                </div>
              </vue-seamless-scroll>
            </div>
          </div>
        </div>
      </div>
    </div>
  </CompOperate>
</template>

<script>
import { v4 as uuid } from "uuid";
import { pxToVw } from "@/utils/common";
import emitter from "@/utils/designer/emitter";
import { buildParentApi } from "@/utils/designer/util";
import vueSeamlessScroll from "vue-seamless-scroll";
import ScrollX from "@c/public/seamlessScroll/ScrollX.vue";
import { arrProcessingData } from "@/utils/biz/common/BizUtils";
import mixin from "@sc/templateDetails/modules/homeMiddle/fieldMixin";
import CompOperate from "@c/public/form-designer/devType/modules/compOperate.vue";

export default {
  name: "scene-window-patientList3-1920-widget",

  componentName: "FieldWidget", //必须固定为FieldWidget，用于接收父级组件的broadcast事件

  mixins: [emitter, mixin],

  components: {
    ScrollX,
    CompOperate,
    vueSeamlessScroll,
  },

  props: {
    widget: Object,
    devType: {
      type: Boolean,
      default: false,
    },
    field: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,
    designState: {
      type: Boolean,
      default: false,
    },
    subFormRowIndex: {
      /* 子表单组件行索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormColIndex: {
      /* 子表单组件列索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormRowId: {
      /* 子表单组件行Id，唯一id且不可变 */ type: String,
      default: "",
    },
    headTitle: {
      type: String,
      default: "",
    },
    visibleTitle: {
      type: Boolean,
    },
    //prop传入的表单JSON配置
    parentApi: {
      type: Object,
      default: () => buildParentApi(),
    },
  },

  data() {
    return {
      widgetKey: uuid(),
      optionsInfo: Object(),
      header: require("@a/images/design/header.jpeg"),
      pause: require("@a/images/design/pause.png"),
      step: null,
    };
  },
  computed: {
    // 滚动配置项
    classOptionPatient() {
      return function (row) {
        let {
          scroll,
          scrollStep,
          patientListCol = 3,
          viewNumber,
        } = this.optionsInfo;
        let flattenArr = this.$lodash.flattenDeep(row);
        let number = viewNumber * patientListCol;
        let fontSize = parseFloat(document.documentElement.style.fontSize);
        let scale = fontSize / 19.2;
        return {
          step: (fontSize / 19.2) * scrollStep * scale, // 数值越大速度滚动越快
          hoverStop: true,
          openTouch: false,
          direction: scroll && flattenArr?.length > number ? 1 : -1, // 0向下 1向上 2向左 3向右
          limitMoveNum:
            scroll && flattenArr?.length > number ? viewNumber + 1 : 99999, // 开始无缝滚动的数据量
        };
      };
    },

    // 设置的行内样式
    getStyle() {
      return function (val) {
        const self = this;
        let info = self.optionsInfo || Array();
        let Obj = Object();
        switch (val) {
          case "area":
            Reflect.set(Obj, "height", pxToVw(info.areaHeight));
            return Obj;
          case "room":
            Reflect.set(Obj, "fontSize", pxToVw(info.roomNameFontSize));
            Reflect.set(Obj, "background", info.roomBackground);
            return Obj;
          case "number":
            Reflect.set(Obj, "fontSize", pxToVw(info.roomNumberFontSize));

            Reflect.set(Obj, "color", info.roomNumberColor);
            return Obj;
          case "patientOrderNo":
            Reflect.set(Obj, "color", info.patientOrderFontColor);
            if (info["patientOrderNoListBackGroundShown"]) {
              Reflect.set(Obj, "background", info.patientOrderBackground);
            } else {
              Reflect.deleteProperty(Obj, "background");
            }
            return Obj;
          case "windowTit":
            Reflect.set(Obj, "fontSize", pxToVw(info.winNumberTitFontSize));

            return Obj;
          case "patientListBackground":
            Reflect.set(Obj, "background", info.patientListBackground);
            return Obj;
          case "title":
            Reflect.set(Obj, "fontSize", pxToVw(info.patientListTitleFontSize));
            Reflect.set(Obj, "fontWeight", info.patientListTitletFontWeight);
            Reflect.set(Obj, "color", info.patientListTitleFontColor);
            Reflect.set(Obj, "background", info.patientListTitleBackground);
            return Obj;
          case "waitPatient":
            let listHeight = info.areaHeight - 128 - 56;
            Reflect.set(
              Obj,
              "lineHeight",
              pxToVw(listHeight / info.viewNumber)
            );
            Reflect.set(Obj, "height", pxToVw(listHeight / info.viewNumber));
            Reflect.set(Obj, "fontWeight", info.patientListFontWeight);
            Reflect.set(Obj, "fontSize", pxToVw(info.patientListFontSize));
            return Obj;
        }
      };
    },

    // 获取科室信息
    getWindowDeptInfo() {
      let devType = this.devType;
      let roomDoctorInfo = this.$store.getters["getWindowDeptInfoInfo"];
      if (devType) {
        return roomDoctorInfo.apiData;
      } else {
        return roomDoctorInfo.mockData;
      }
    },

    // 原始患者数据
    originalInfo() {
      let roomDoctorInfo = this.$store.getters["getWindowDynamicsListInfo"];
      console.log(`原始患者数据-${JSON.stringify(roomDoctorInfo)}`);
      let devType = this.devType;
      return devType ? roomDoctorInfo.apiData : roomDoctorInfo.mockData;
    },

    //处理患者信息
    getRoomDoctorInfo() {
      let { patientListCol, viewNumber } = this.optionsInfo;
      let totalNumber = viewNumber * patientListCol || 9;
      let patientInfo = this.originalInfo || Array();
      // console.log(`患者信息-${JSON.stringify(patientInfo)}`);
      let summary = this.$lodash.map(patientInfo);
      let flattenArr = this.$lodash.flattenDeep(summary);
      // 不足-补足指定的条数
      if (!!flattenArr && flattenArr.length > totalNumber) {
        return this.$lodash.chunk(flattenArr, patientListCol || 3);
      } else {
        let fillArr = new Array(totalNumber - flattenArr.length).fill({});
        let mergeArr = [...flattenArr, ...fillArr];
        return this.$lodash.chunk(mergeArr, patientListCol || 3);
      }
    },

    // 子数组填充数据
    getPatientChildList() {
      return function (row) {
        let { patientListCol } = this.optionsInfo;
        let len = row?.length;
        if (len >= patientListCol) {
          return row;
        } else {
          let fillArr = Array(patientListCol - len).fill({});
          return [...row, ...fillArr];
        }
      };
    },

    // 患者内容
    getPatientContent() {
      return function (row) {
        let { patientOrderNoShown, patientOrderFontColor, patientFontColor } =
          this.optionsInfo;
        if (patientOrderNoShown) {
          return `<div style='color:${
            patientFontColor || "transparent"
          }'><span style='color:${patientOrderFontColor || "transparent"}'>${
            row.windowNum || "\u00a0"
          }</span>&nbsp;${row.patientName || "\u00a0"}</div>`;
        } else {
          return `<div style='color:${patientFontColor || "transparent"}'>${
            row.patientName || "\u00a0"
          }</div>`;
        }
      };
    },
  },

  created() {
    this.registerToRefList();
    this.initEventHandler();
    this.handleOnCreated();
  },

  mounted() {
    this.handleOnMounted();
    this.executeMethod();
  },

  methods: {
    // 接收父组件传递过来的数据
    executeMethod(key, data) {
      // alert(key);
      switch (key) {
        case "roomDoctorInfo":
          console.log(`医生-患者-信息-${JSON.stringify(data)}`);
          let roomList = this.$lodash.cloneDeep(data);
          let res = [];
          if (roomList.length > 0) {
            res = roomList[0].waitingPatientList;
          }
          this.$store.dispatch(
            "setWindowDynamicsInfo",
            this.$lodash.cloneDeep(res)
          );
          break;
        case "roomDeptInfo":
          console.log(`科室诊室信息-${data}`);
          this.$store.dispatch(
            "setWindowDeptInfo",
            this.$lodash.cloneDeep(data)
          );
          this.$store.dispatch("setRoomDeptInfo", data);
          break;
        case "refreshData":
          // let roomList2 = this.$lodash.cloneDeep(data);
          // let res2 = [];
          // if (roomList2.length > 0) {
          //   res2 = roomList2[0].waitingPatientList;
          // }
          // this.$store.dispatch(
          //   "setWindowDynamicsInfo",
          //   this.$lodash.cloneDeep(res2)
          // );
          break;
      }
    },

    handleScrollEnd() {
      console.log("滚动结束");
    },
  },

  watch: {
    field: {
      handler: function (val) {
        this.widgetKey = uuid();
        let key = val.options.config;
        this.optionsInfo = val.options[key];
      },
      deep: true,
      immediate: true,
    },
  },

  destroyed() {
    this.unregisterFromRefList();
  },
};
</script>

<style lang="scss" scoped>
.scene-window-widget {
  color: #333;
  height: 150px;
  font-size: 40px;
  padding: 28px 30px;
  box-sizing: border-box;
  flex: inherit;
  flex-direction: column;
  justify-content: space-between;
  background: transparent;
  overflow: hidden;

  .window-area {
    height: 100%;
    display: flex;
    flex-direction: column;
    background: transparent;

    .replenish {
      width: 100%;
      font-size: 80px;
      color: #0059b3;
      line-height: 112px;
      text-align: center;
      font-style: normal;
      @include fontWeight();
    }

    .window-info {
      .flex-item {
        overflow: hidden;
        color: #ffffff;
        display: flex;
        text-align: center;
        align-items: center;
        flex-direction: column;
        justify-content: center;
        border: none;
        position: relative;

        .flex-title {
          width: 100%;
          height: 160px;
          background: #003f76;
          position: absolute;
          top: 0;
        }

        .flex-number-style {
          width: 100%;
          padding-top: 160px;
        }
      }

      .flex-box-left-1 {
        height: auto;
        display: flex;
        text-align: left;
        flex: 1;
        overflow: hidden;
        box-sizing: border-box;
        flex-basis: calc(30% - 16px);
        font-weight: bolder;
        font-size: 460px;
        border-radius: 20px;
        overflow: hidden;
        box-sizing: border-box;
        margin-right: 16px;
        box-shadow: 30px 30px 30px -10px rgba(0, 0, 0, 0.15),
          inset -1px -1px 10px rgba(0, 0, 0, 0.2);
      }
      .box-shadow-1 {
        box-shadow: 30px 30px 30px -10px rgba(0, 0, 0, 0.15),
          inset 15px 15px 10px rgba(255, 255, 255, 0.75),
          inset -1px -1px 10px rgba(0, 0, 0, 0.2);
      }

      .flex-box-right-1 {
        // border: 1px #dedede solid;
        height: auto;
        display: flex;
        text-align: left;
        flex: 1;
        border-radius: 4px;
        overflow: hidden;
        box-sizing: border-box;
        flex-basis: calc(70%);
        display: flex;
        flex-grow: 1;
        height: 100%;
        flex-direction: column;
        border-radius: 20px;
        box-sizing: border-box;
        overflow: hidden;

        .title {
          font-size: 64px;
          overflow: hidden;
          text-align: center;
          @include singleEllipsis(100%);
          height: 128px;
          line-height: 128px;
          align-content: center;
          align-self: center;
          align-items: center;
        }
        .right-title-border-1 {
          border-bottom: 6px solid #ffff00;
        }
        .content-area {
          display: flex;
          width: 100%;
          height: calc(100% - 128px);
          // background: white;
          overflow: hidden;
          backface-visibility: hidden;
          perspective: 1000;
          will-change: transform; /* 提示浏览器这个元素将会变化，优化性能 */
          transform: translateZ(0); /* 触发硬件加速，减少重绘和回流 */

          .scroll {
            width: 100%;
            /* 确保内容样式不会导致不必要的布局变化 */
            white-space: nowrap;
            font-smoothing: antialiased; /* 抗锯齿，使字体更清晰 */
          }

          .inside-content {
            display: flex;
            flex-direction: column;
            width: 100%;
            align-items: center;
            align-self: center;
            align-content: center;
            justify-content: center;
            /* 确保内容样式不会导致不必要的布局变化 */
            white-space: nowrap;
            font-smoothing: antialiased; /* 抗锯齿，使字体更清晰 */

            .wait-patient-inside {
              color: #333333;
              box-sizing: border-box;
              font-size: 32px;
              width: 100%;
              display: flex;
              flex-direction: row;
              overflow: hidden;
              // background: rgba(255, 255, 255, 1);
              text-align: center;
              border-bottom: 1px rgba(51, 51, 51, 0.2) solid;
              /* 确保内容样式不会导致不必要的布局变化 */
              white-space: nowrap;
              font-smoothing: antialiased; /* 抗锯齿，使字体更清晰 */

              .child-item {
                flex-grow: 1;
                flex-shrink: 0;
                flex-basis: 0;
                @include singleEllipsis(100%);
                /* 确保每个滚动项的样式不会导致布局抖动 */
                display: inline-block;
                vertical-align: top; /* 确保垂直对齐一致 */
                font-smoothing: antialiased; /* 抗锯齿，使字体更清晰 */
              }
            }
          }

          .wait-patient-inside-empty {
            min-height: 480px;
            margin-top: 10px;
            // background: white;
          }
        }
      }
    }
  }
}
</style>
